// 把时间戳转为时间
export function timestamp(number, format) {
  // this.timeStamp(new Date(value).getTime() / 1000, 'Y-M-D')
  var formateArr = ["Y", "M", "D", "h", "m", "s"];
  var returnArr = [];
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumberForTimestamp(date.getMonth() + 1));
  returnArr.push(formatNumberForTimestamp(date.getDate()));

  returnArr.push(formatNumberForTimestamp(date.getHours()));
  returnArr.push(formatNumberForTimestamp(date.getMinutes()));
  returnArr.push(formatNumberForTimestamp(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
// 123
function formatNumberForTimestamp(n) {
  n = n.toString();
  return n[1] ? n : "0" + n;
}
function formatDateFn(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}
// 把new Date()转为时间
export function formatDate(date, fmt) {
  return formatDateFn(date,fmt);
}
function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}
// 替换特殊字符，获取主标题
export function replace_some_chart(parm) {
  parm = parm.trim();
  let arr = ["_", " ", "—", "-", "「", ":", "：", "(", ")", "（", "）"];
  arr.forEach(element => {
    parm =
      parm.indexOf(element) != -1 ? parm.slice(0, parm.indexOf(element)) : parm;
  });
  return parm;
}
// 函数防抖动
export function debounce(func, delay) {
  let timer;
  return function(...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// 数组去重复
export function unique(arr) {
  if (!Array.isArray(arr)) {
    return;
  }
  var array = [];
  for (var i = 0; i < arr.length; i++) {
    if (array.indexOf(arr[i]) === -1) {
      array.push(arr[i]);
    }
  }
  return array;
}

// 时间戳转化成日期
// 2020/7/20
export function timestampToTime(timestamp) {
  var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y = date.getFullYear();
  let M =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  // let D = date.getDate() ;
  let D =
    date.getDate() + 1 < 10 ? "0" + (date.getDate() + 1) : date.getDate() + 1;
  let h = date.getHours() + ":";
  let m = date.getMinutes() + ":";
  let s = date.getSeconds();
  return Y + "/" + M + "/" + D; //时分秒可以根据自己的需求加上
}
// 数字格式化
export function format_num(num) {
  if (!num) return num;
  if (num > 99999999) num = (num / 100000000).toFixed(1) + "亿";
  else if (num > 9999) num = (num / 10000).toFixed(1) + "w";
  else if (num < -99999999) num = (num / 100000000).toFixed(1) + "亿";
  else if (num < -9999) num = (num / 10000).toFixed(1) + "w";
  return num;
}
// 数字格式化
export function fornum(num) {
  if (!num) return num;
  if (num > 99999999) num = (num / 100000000).toFixed(1);
  else if (num > 9999) num = (num / 10000).toFixed(1);
  else if (num < -99999999) num = (num / 100000000).toFixed(1);
  else if (num < -9999) num = (num / 10000).toFixed(1);
  return num;
}
//毫秒格式化
export function format_time(num) {
  if (!num) return num;
  let num1 = num / 1000;
  let d = parseInt(num1 / 86400);
  let h = parseInt((num1 % 86400) / 3600);
  let m = parseInt(((num1 % 86400) % 3600) / 60);
  let s = Math.round(((num1 % 86400) % 3600) % 60);
  if (d > 0) {
    return (num1 = d + "天" + h + "小时" + m + "分" + s + "秒");
  } else if (h > 0) {
    return (num1 = h + "小时" + m + "分" + s + "秒");
  } else if (m > 0) {
    return (num1 = m + "分" + s + "秒");
  } else {
    return (num1 = s + "秒");
  }
}
// 百分数格式化 num要格式化的数据 fixNum 保留几位小数 isAbs是否取绝对值
export function formatRate(num, fixNum, isAbs) {
  if (num == 0) {
    return 0;
  } else if (num == 1) {
    return 100 + "%";
  } else if (num == "") {
    return "";
  } else {
    // 取绝对值
    if (isAbs == 1) {
      return Math.abs((num * 100).toFixed(fixNum)) + "%";
    } else {
      return (num * 100).toFixed(fixNum) + "%";
    }
  }
}
// 去除字符串两边的空白（空格）不用trim怕有的浏览器不兼容

export function initDateInterval(day){ //距离今天的区间日期
  var toDay = day - 1;
  let myDate = new Date(); 
  myDate.setDate(myDate.getDate() - toDay);
  let startDate = formatDate(new Date(myDate), "yyyy-MM-dd");
  let endDate = formatDate(new Date(), "yyyy-MM-dd");
  
  return [startDate, endDate]; //初始化日期
}

export function getStr(len){ //获取随机字符串
  len = len || 32;
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  let maxPos = $chars.length;
  let pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

export function isWX(){ //是否为微信端内浏览器
  let viewer = navigator.userAgent.toLowerCase();
  return (viewer.match(/MicroMessenger/i) == 'micromessenger');
};

function isZsjxAppFn(){ //是否为掌上精选app
  // return Boolean(navigator.userAgent.indexOf('_ZHANGSHANGJINGXUANAPP_') > -1 && window.appBridgObj);
  return Boolean(navigator.userAgent.indexOf('_ZHANGSHANGJINGXUANAPP_') > -1);
};
export let isZsjxApp = isZsjxAppFn();

function isMoblieFn(){ //判断是否是移动端（包括平板）
  let check = false;
    (function (a) {
      if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true;
    })(navigator.userAgent || navigator.vendor || window.opera);
  return check;
};
export let isMoblie = isMoblieFn();

/*判断是否为安卓、ios*/
function OSTypeFn() {
  let u = navigator.userAgent;
  if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
    return 'android'
  } else if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return 'ios'
  } else {
    return 'pc'
  }
};

export let OSType = OSTypeFn();


function setCookieFn(cname,cvalue,exdays){
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookieFn(cname){
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) {
      var c = ca[i].trim();
      if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
  }
  return "";
}
function checkCookieFn(){
  var user=getCookie("username");
  if (user!=""){
      alert("欢迎 " + user + " 再次访问");
  }
  else {
      user = prompt("请输入你的名字:","");
        if (user!="" && user!=null){
          setCookie("username",user,30);
      }
  }
}
export let setCookie = setCookieFn;
export let getCookie = getCookieFn;
export let checkCookie = checkCookieFn;

export function trimStr(word) {
  return word.replace(/^\s+|\s+$/gm, "");
}
function getUrlPms(){
  let search = window.location.search.substr(1) || window.location.hash.split("?")[1];
  if (search) {
    let params = search.split('&'),
    urlParams = {};
    for (let i = 0; i < params.length; i++) {
      let thisData = params[i].split('=');
      urlParams[thisData[0]] = decodeURIComponent(thisData[1]);
    }
    return urlParams;
  } else {
    return {};
  }
};
export let urlPms = getUrlPms();

// 日期格式化
export function formatDateNew (date, typeStr) {
  let thisDate = new Date();
  if (date) {
    thisDate = new Date(date);
  } 
  let YY = thisDate.getFullYear(),
    Y = YY.toString().substr(2, 2),
    M = 1 + thisDate.getMonth(),
    MM = M > 9 ? M : '0' + M,
    D = thisDate.getDate(),
    DD = D > 9 ? D : '0' + D,
    h = thisDate.getHours(),
    hh = h > 9 ? h : '0' + h,
    m = thisDate.getMinutes(),
    mm = m > 9 ? m : '0' + m,
    s = thisDate.getSeconds(),
    ss = s > 9 ? s : '0' + s;
    let formatStr = typeStr
    .replace(/YY/g, YY)
    .replace(/Y/g, Y)
    .replace(/MM/g, MM)
    .replace(/M/g, M)
    .replace(/DD/g, DD)
    .replace(/D/g, D)
    .replace(/hh/g, hh)
    .replace(/h/g, h)
    .replace(/mm/g, mm)
    .replace(/m/g, m)
    .replace(/ss/g, ss)
    .replace(/s/g, s);
    return formatStr;
};
// 1574954488000

// 获取固定日期的星期
export function formatDateWeek(time){
    //初始化日期时间
    let myDate = new Date(time);
    // var year=myDate.getFullYear();    
    // var month=myDate.getMonth()+1;  
    // var date=myDate.getDate(); 
    // console.log(year+"-"+month+"-"+date);
    let str = "星期" + "日一二三四五六".charAt(myDate.getDay());
    return str;
}
export function levelName(level){ //获取等级对应名称
  let name = '';
  if(level == 3){
    name = '体验版';
  }else if(level == 4){
    name = 'VIP';
  }else if(level == 1){
    name = 'SVIP';
  }else if(level == 2){
    name = 'Plus';
  }else if(level == 5){
    name = 'SVIP';
  }else{
      name = '免费版用户';
  }
  return name;
}
export function levelVersions(level){  //获取等级对应版本
  if(level == '0' || level == '3'){ //如果是免费版或者体验版，ui不展示对应版本
    return false;
  }else{
    if(level == 5){
      return '个人版';
    }else{
      return '企业版';
    }
  }
}
export function getClientHeight(){  //取窗口可视范围的高度
  let clientHeight=0;
  if(document.body.clientHeight && document.documentElement.clientHeight){
    clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }else{
    clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  return clientHeight;
}
export function getScrollTop(){  //取窗口可视范围的高度
  let scrollTop=0;
  if(document.documentElement && document.documentElement.scrollTop){
    scrollTop = document.documentElement.scrollTop;
  }else if(document.body){
    scrollTop = document.body.scrollTop;
  }
  return scrollTop;
}